package com.suray.system.run.device.free;

import com.suray.basic.wcs.plc.core.Plc;
import com.suray.basic.wcs.plc.enums.Location;
import com.suray.basic.wcs.plc.pojo.DeviceBase;
import com.suray.basic.wcs.plc.pojo.oper.lifter.LifterOper;
import com.suray.wcs.service.test.base.BaseThread;
import com.suray.wcs.service.util.WcsUtil;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * Plc设备空闲调度
 */
@Component
public class PlcDeviceFree extends BaseThread {

    /**
     * 提升机设备空闲动作
     */
    List<LifterDeviceFreeAction> lifterDeviceFreeActions;

    List<DeviceBase> deviceList;

    public PlcDeviceFree() {
        super("Plc设备空闲", 5000);

        lifterDeviceFreeActions = new ArrayList<>();
        deviceList = new ArrayList<>();

        this.start();
    }

    @Override
    protected void init() {
        checkDevice();
    }

    private void checkDevice() {
        checkLifter();
    }

    private void checkLifter() {
        for (DeviceBase deviceBase : Plc.deviceLifterCoordMap.values()) {
            if (deviceList.contains(deviceBase)) {
                continue;
            }

            if (deviceBase.getLocation() != null && deviceBase.getLocation() == Location.INSIDE) {
                lifterDeviceFreeActions.add(new LifterDeviceFreeAction((LifterOper) deviceBase));
                deviceList.add(deviceBase);
            }
        }
    }

    @Override
    protected void process() {
        checkDevice();
        lifterDeviceFree();
    }

    /**
     * 提升机空闲
     */
    private void lifterDeviceFree() {
        lifterDeviceFreeActions.forEach(lifterDeviceFreeAction -> {
            try {
                lifterDeviceFreeAction.lifterFreeCheck();
            } catch (Exception e) {
                WcsUtil.exceptionLog(e, this.getClass());
            }
        });
    }
}
